//
//  RemindVC.swift
//  chat
//
//  Created by 崔世强 on 2024/8/27.
//  Copyright © 2024 崔世强. All rights reserved.
//

import UIKit
import Kingfisher
import Toast_Swift

private let collectionviewcell = "collectionviewcell"

class RemindVC: UIViewController {
    var groupId:Int = 0
    
    lazy var tableView:UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .singleLine
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(ContactCell.self, forCellReuseIdentifier: ContactCell.contactCellId)
        tableView.rowHeight = 55
        return tableView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        setSection()
        setUI()
        
        let closeBarItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(cancelSelect))
        self.navigationItem.rightBarButtonItems = [closeBarItem]
    }
    
    @objc func cancelSelect() {
        self.dismiss(animated: true, completion: nil)
    }
    
    
    var contactList = [ChatGroupMember]()
    let collation = UILocalizedIndexedCollation.current()
    var sectionsArray: [[ChatGroupMember]] = [[ChatGroupMember]]()
    
    private var keysArray:[String] = []
    
    let service = GroupService()
    func loadData() {
        do {
            self.contactList = try self.service.getChatGroupMembers(self.groupId, limit: Int.max)
            print("self.contactList.count\(self.contactList.count)")
            var indexToRemove: Int = 0
            for i in 0 ..< self.contactList.count {
                let chatGroupMember = self.contactList[i]
                if chatGroupMember.userId == AppStatusManager.instance.userLoginStatus.1 {indexToRemove = i}
            }
            
            self.contactList.remove(at: indexToRemove)
            
            print("self.contactList.count\(self.contactList.count)")
        }catch {
            print(error)
        }
    }
    
    func setSection(){
        UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: contactList, collationStringSelector: #selector(getter: ChatGroupMember.nickName)) { (dataArray,titleArray) in
            self.sectionsArray = dataArray
            self.keysArray    = titleArray
            self.tableView.reloadData()
        }
    }
    
    //设置UI
    func setUI(){
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
}

//扩展

extension RemindVC:UITableViewDataSource, UITableViewDelegate  {
    internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.contactCellId, for: indexPath) as! ContactCell
        let chatContact = sectionsArray[indexPath.section][indexPath.row]
        cell.nameLabel.text = chatContact.nickName
        
        cell.headimage.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(chatContact.contact?.avatar ?? "unknown")!), placeholder: UIImage.init(named:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        
        cell.tagbutton.isHidden = true
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return keysArray.count
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return keysArray[section]
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 23
    }
    
    //设置索引标题
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }
    
    //关联搜索
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        if index == 0{
            tableView.setContentOffset(CGPoint.zero, animated: false)
            return 0
        }
        return index
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if sectionsArray.count == 0 {
            return 0
        }
        return sectionsArray[section].count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.dismiss(animated: true, completion: nil)
        let member = sectionsArray[indexPath.section][indexPath.row]
        NotificationCenter.default.post(name: NSNotification.Name(remindedGroupMem), object: self, userInfo: ["member":member])
    }
}
